package com.marketlive.system.keymanagement;

/*
(C) Copyright MarketLive. 2006. All rights reserved.
MarketLive is a trademark of MarketLive, Inc.
Warning: This computer program is protected by copyright law and international treaties.
Unauthorized reproduction or distribution of this program, or any portion of it, may result
in severe civil and criminal penalties, and will be prosecuted to the maximum extent
possible under the law.
*/

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.NoSuchPaddingException;

/**
 * The class that drives the KeyManagement package.
 */
public class KMDriver {

    final static String KEY_TYPE = "AES";    // Default symmetric key type
    final static short KEY_SIZE = 256;       // Default symmetric key size
    final static String KS_TYPE = "JCEKS";   // Default keystore type

    /****************************************
     *  MAIN
     *  @param args
     ****************************************/

    public static void main(String[] args) {
        // Display usage
        if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
            System.out.println("\nUsage: java KMDriver <command-option> [parameters]\n\n" +
                "The following command-options are available:\n\n" +
                "createkek:     Create a new Key Encrypting Key\n" +
                "decryptxml:    Decrypt a previously encrypted XML file\n" +
                "help:          Display this usage message\n" +
                "migratekek:    Migrate a 5.3.x KEK file to 5.4.x\n" +
                "rotatekey:     Rotate encryption key\n");
            return;
        }

        /***********************************
         *  CREATE KEY ENCRYPTING KEY (KEK)
         ***********************************/
        if (args[0].equalsIgnoreCase("createkek")) {
            if (args.length < 3) {
                System.out.println("\nUsage: java KMDriver createkek " +
                    " <kekparams-directory-location> <db.properties-location>\n");
                return;
            }
            try {
                String newkeycode = Utilities.createKEKParams(args[1], args[2]);
                if (newkeycode == null)
                    System.out.println("Creation of KEK parameters failed; check logs");
                else
                    System.out.println("KEK parameters were successfully created; new keycode is " + newkeycode);

            } catch (InvalidLocationException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidEnvironmentException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (OtherKeyMgtException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NonexistentJDBCParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            }
        /*********************
         *  DECRYPT XML FILE
         *********************/
        } else if (args[0].equalsIgnoreCase("decryptxml")) {
            if (args.length < 4) {
                System.out.println("\nUsage: java KMDriver decryptxml" +
                        " <kekparams-file-location> <db.properties-location> <decryptxml-config-directory-location>\n");
                return;
            }
            try {
                DecryptXML.execute(args[1], args[2], args[3]);
            } catch (FileNotFoundException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidLocationException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NonexistentJDBCParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (OtherKeyMgtException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidKeyException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NoSuchAlgorithmException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidKeySpecException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NoSuchPaddingException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidAlgorithmParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (UnsupportedEncodingException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NonexistentKEKParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            }
        /*************************************
         *  MIGRATE A 5.3.x KEK FILE TO 5.4.x
         *************************************/
        } else if (args[0].equalsIgnoreCase("migratekek")) {
            if (args.length < 3) {
                System.out.println("\nUsage: java KMDriver migratekek" +
                        " <5.3.x-kek-file-location> <db.properties-location>\n");
                return;
            }
            try {
                String newkeycode = Utilities.migrateKEK(args[1], args[2]);
                if (newkeycode == null) {
                    System.out.println("Migration of 5.3.x KEK failed; check logs");
                }
                else {
                    System.out.println("5.3.x KEK successfully migrated to 5.4.x; new keycode is " + newkeycode);
                }
            } catch (InvalidLocationException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NonexistentJDBCParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidEnvironmentException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (OtherKeyMgtException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (FileNotFoundException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            }
        /****************************************
         *  ROTATE PUBLIC/PRIVATE KEY-PAIR IN DB
         ****************************************/
        } else if (args[0].equalsIgnoreCase("rotatekey")) {
            if (args.length < 3) {
                System.out.println("\nUsage: java KMDriver rotatekey" +
                        " <kekparams-file-location> <db.properties-location>\n");
                return;
            }
            try {
                String newkeycode = Utilities.rotateKey(args[1], args[2]);
                if (newkeycode == null) {
                    System.out.println("Key-pair rotation failed; check logs");
                }
                else {
                    System.out.println("Key-pair successfully rotated; new keycode is " + newkeycode);
                }
            } catch (InvalidLocationException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NonexistentJDBCParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (InvalidEnvironmentException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (OtherKeyMgtException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (FileNotFoundException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            } catch (NonexistentKEKParameterException e) {
                System.err.println("\nERROR: " + e.getLocalizedMessage() + '\n');
            }
        } else {
            System.out.println("\nERROR: Invalid option: " + args[0]);
            System.out.println("\nUsage: java KMDriver <command-option> [parameters]\n\n" +
                "The following command-options are availabe:\n\n" +
                "createkek:     Create a new Key Encrypting Key\n" +
                "decryptxml:    Decrypt a previously encrypted XML file\n" +
                "help:          Display this usage message\n" +
                "migratekek:    Migrate a 5.3.x KEK file to 5.4.x\n" +
                "rotatekey:     Rotate encryption key\n");
        }
    }
}